package com.heatup.apt.management.service.coach.impl;

import java.util.*;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.heatup.apt.common.dao.CoachPrivateSortMapper;
import com.heatup.apt.model.CoachPrivateSort;
import com.heatup.apt.model.CoachPrivateSortModel;
import com.heatup.apt.model.Resource;
import com.heatup.apt.model.ResourceExample;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.heatup.apt.common.constants.CoachConstants;
import com.heatup.apt.common.constants.ResourceContants;
import com.heatup.apt.common.dao.ResourceMapper;
import com.heatup.apt.common.dao.coach.CoachInfoMapper;
import com.heatup.apt.common.dao.store.StoreCoachMapper;
import com.heatup.apt.common.util.StringUtil;
import com.heatup.apt.management.service.coach.CoachService;
import com.heatup.apt.model.api.ResourceModel;
import com.heatup.apt.model.coach.CoachInfo;
import com.heatup.apt.model.coach.CoachStoreInfo;
import com.heatup.apt.model.store.StoreCoach;

/**
 *
 */
@Service
public class CoachServiceImpl extends SuperServiceImpl<CoachInfoMapper, CoachInfo> implements CoachService {

    private static final Logger log = LoggerFactory.getLogger(CoachServiceImpl.class);

    @Autowired
    private CoachInfoMapper coachInfoMapper;

    @Autowired
    private StoreCoachMapper storeCoachMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private CoachPrivateSortMapper coachPrivateSortMapper;

    @Override
    public boolean updateCoach(CoachInfo coachInfo) {
        int count = coachInfoMapper.updateSelectiveById(coachInfo);
        return count > 0;
    }

    @Override
    public int addCoach(CoachInfo coachInfo) {
        int count = coachInfoMapper.insertSelective(coachInfo);
        if (count > 0) {
            return coachInfo.getId();
        } else {
            return 0;
        }
    }

    @Override
    public Map<String, Object> queryCoachList(String coachName, int storeId, int level, String status, int page, int limit) {
        Map<String, Object> map = new HashMap<>();
        int offset = 0;
        if (page > 1) {
            offset = (page-1) * limit;
        }
//        CoachInfoExample coachInfoExample = new CoachInfoExample();
//        coachInfoExample.or().andNickNameLike(coachName).andStatusEqualTo(status).andLevelEqualTo(level);
//        RowBounds rowBounds = new RowBounds(page, limit);
//        List<CoachInfo> coachInfoList = coachInfoMapper.selectByExampleWithRowbounds(coachInfoExample, rowBounds);
        List<CoachStoreInfo> coachInfoList = coachInfoMapper.selectCoachByCondition(coachName, storeId, level, status, offset, limit);
        int count = coachInfoMapper.selectCoachByConditionCount(coachName, storeId, level, status);
        int pageCount = 0;
        if (count % limit == 0) {
            pageCount = count / limit;
        } else {
            pageCount = count / limit + 1;
        }
        map.put("pageCount", pageCount);
        map.put("page", page);
        map.put("size", limit);
        map.put("totalCount", count);
        map.put("coachInfoList", coachInfoList);
        return map;
    }

    @Override
    public CoachStoreInfo showCoachById(int coachId) {
        CoachStoreInfo coachInfo = coachInfoMapper.selectStoreCoachInfo(coachId);
        return coachInfo;
    }

    @Override
    public int addStoreCoach(StoreCoach storeCoach) {
        //TODO需要增加门禁类型和门禁ID
        int count = storeCoachMapper.insert(storeCoach);
        return count;
    }

   
    @Override
    public void addResource (CoachInfo coachInfo, int type, String images) {
        if (StringUtil.isNotEmpty(images)) {
            String[] imgs = images.split(",");
            //保存图片 视频连接
            for (String img : imgs) {
                Resource resource = new Resource();
                resource.setUrl(img);
               // resource.setPreviewUrl(img);
                resource.setLink(img);
                resource.setResType(String.valueOf(type));//1:图片 2:视频
                resource.setParentType("3");//教练
                resource.setResKey("common");
                //resource.setTitle(coachInfo.getNickName());
                resource.setParentId(coachInfo.getId());
                resource.setResourceParentId(coachInfo.getId());
                resource.setCreatedBy(1);//TODO 增加创建人
                resource.setCreatedTime(new Date());
                resourceMapper.insert(resource);
            }
        }
    }
    @Override
    public List<CoachInfo> queryAllCoachInfo() {
        EntityWrapper<CoachInfo> entityWrapper = new EntityWrapper<CoachInfo>();
        entityWrapper.where("status = {0}", CoachConstants.CoachStatus.online.getStatus());
        return coachInfoMapper.selectList(entityWrapper);
    }

    /**
     * 根据教练id查询教练对应图片/视频／文章
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, List<ResourceModel>> selectResourceByCoachId(int id) {
        ResourceExample resourceExample = new ResourceExample();
        resourceExample.or().andParentIdEqualTo(id).andParentTypeEqualTo("3");//查询图片资源
        List<Resource> resources = resourceMapper.selectByExample(resourceExample);
        if (resources != null && resources.size() > 0) {
            Map<String, List<ResourceModel>> resourceMap = new HashMap<String, List<ResourceModel>>();
            for (Resource resource : resources) {
                List<ResourceModel> resourceModels = null;
                String type = ResourceContants.ResourceResTypeEnum.getResType(resource.getResType()).getTitle();
                if (!Strings.isNullOrEmpty(resource.getResKey()) && resource.getResKey().equals("top_banner")) {
                    type = resource.getResKey();
                }
                if (resourceMap.containsKey(type)) {
                    resourceModels = resourceMap.get(type);
                } else {
                    resourceModels = Lists.newArrayList();
                }
                ResourceModel resourceModel = new ResourceModel();
               // resourceModel.setPreviewUrl(resource.getPreviewUrl());
                resourceModel.setTitle(resource.getTitle());
                resourceModel.setLink(resource.getLink());
                resourceModel.setUrl(resource.getUrl());
                resourceModel.setId(resource.getId());
                resourceModels.add(resourceModel);
                resourceMap.put(type, resourceModels);
            }
            return resourceMap;
        }
            return null;
    }

    /**
     * 根据教练id删除教练对应图片/视频／文章
     *
     * @param id
     * @return
     */
    @Override
    public void deleteResource(int id,String fileName) {
        ResourceExample resourceExample = new ResourceExample();
        resourceExample.or().andParentIdEqualTo(id).andParentTypeEqualTo("3").andLinkLike("%"+fileName+"%");//查询图片资源
        resourceMapper.deleteByExample(resourceExample);
    }

    /**
     * 根据resource id修改教练对应图片/视频／文章
     *
     * @param record
     * @return
     */
    @Override
    public void updateResource(Resource record) {
        Resource rec = new Resource();
        rec.setLink(record.getLink());
        ResourceExample resourceExample = new ResourceExample();
        resourceExample.or().andIdEqualTo(record.getId());
        resourceMapper.updateByExampleSelective(rec,resourceExample);
    }

    /**
     * 教练保存
     * @param coachInfo
     * @return
     */
    @Override
    @Transactional
    public boolean saveCoach(CoachInfo coachInfo) {

        int result;
        if (coachInfo == null) {
            return false;
        }
        coachInfo.setStatus(CoachConstants.CoachStatus.online.getStatus());
        if (StringUtils.isNotBlank(coachInfo.getAuthInfo())) {
            coachInfo.setAuthInfo(coachInfo.getAuthInfo().replaceAll(",","、"));
        }
        if (StringUtils.isNotBlank(coachInfo.getGoodCourse())) {
            coachInfo.setGoodCourse(coachInfo.getGoodCourse().replaceAll(",","#"));
        }

        if (coachInfo.getIsTeam() == null) {
            coachInfo.setIsTeam(CoachConstants.CoachSupportStatus.UN_SUPPORT.getIndex());
        }
        if (coachInfo.getIsPrivate() == null) {
            coachInfo.setIsPrivate(CoachConstants.CoachSupportStatus.UN_SUPPORT.getIndex());
        }
        if (coachInfo.getIsCamp() == null) {
            coachInfo.setIsCamp(CoachConstants.CoachSupportStatus.UN_SUPPORT.getIndex());
        }
        if(!StringUtil.isEmpty(coachInfo.getTeachCourse())){
        	coachInfo.setTeachCourse(coachInfo.getTeachCourse().replaceAll(",","#"));
        }
        if (coachInfo.getIsPrivateCoachSort() != null && coachInfo.getIsPrivateCoachSort().equals(1) && coachInfo.getId() != null) {
            //加入私教轮排
            joinCoachToCoachPrivateSort(coachInfo);
        } else if (coachInfo.getIsPrivateCoachSort() != null && coachInfo.getIsPrivateCoachSort().equals(2)){
            //移除私教轮排
            CoachPrivateSort coachPrivateSort = new CoachPrivateSort();
            coachPrivateSort.setCoachId(coachInfo.getId());
            coachPrivateSortMapper.deleteSelective(coachPrivateSort);
        }


        if (coachInfo.getId() != null) {
            // 主教练
            if(coachInfo.getIsChiefCoach() == 1){
                coachInfo.setParentCoachId(coachInfo.getId());
            }
            coachInfoMapper.updateSelectiveById(coachInfo);

            //清理关联资源
            resourceMapper.deleteByCoachId(coachInfo.getId());
            storeCoachMapper.deleteByCoachId(coachInfo.getId());
        } else {
            coachInfo.setJoinTime(new Date());
            coachInfo.setCreatedTime(new Date());
            result = coachInfoMapper.insertSelective(coachInfo);
            // 主教练
            if(coachInfo.getIsChiefCoach() == 1){
                coachInfo.setParentCoachId(coachInfo.getId());
                coachInfoMapper.updateSelectiveById(coachInfo);
            }
            if (result > 0) {
                Integer coachCount = coachPrivateSortMapper.selectCount(null);
                if (coachCount == null || coachCount == 0) {
                    //需要初始化教练轮排表数据
                    //查询所有在职且支持私教的教练列表
                    CoachInfo coachInfoQuery = new CoachInfo();
                    coachInfoQuery.setIsPrivate(CoachConstants.CoachSupportStatus.SUPPORT.getIndex());
                    coachInfoQuery.setIsPrivateCoachSort(1);
                    coachInfoQuery.setStatus(CoachConstants.CoachStatus.online.getStatus());
                    EntityWrapper<CoachInfo> entityWrapper = new EntityWrapper<>(coachInfoQuery);

                    List<CoachInfo> coachInfoList = coachInfoMapper.selectList(entityWrapper);
                    List<CoachPrivateSort> coachPrivateSortList = new ArrayList<>();

                    if (coachInfoList != null && coachInfoList.size() > 0) {

                        for (int i = 0; i < coachInfoList.size() ; i++) {
                            CoachPrivateSort coachPrivateSort = new CoachPrivateSort();
                            coachPrivateSort.setSortNow(1);//初始化都为1
                            coachPrivateSort.setCoachId(coachInfoList.get(i).getId());
                            coachPrivateSort.setSortNum(i);
                            coachPrivateSort.setCreatedBy(-1);
                            coachPrivateSort.setStatus(1);
                            coachPrivateSort.setCreatedTime(new Date());

                            coachPrivateSortList.add(coachPrivateSort);
                        }
                    }
                    if (coachPrivateSortList != null && coachPrivateSortList.size() > 0) {
                        int r = coachPrivateSortMapper.insertBatch(coachPrivateSortList);
                        if (r > 0) {
                            log.info("保存教练初始化教练排序数据成功! 成功插入 " + r + "条数据");
                        }
                    }
                }
                joinCoachToCoachPrivateSort(coachInfo);
            }
        }

       
        StoreCoach storeCoach = new StoreCoach();
        storeCoach.setCoachId(coachInfo.getId());
        storeCoach.setStoreId(coachInfo.getStoreId());
        storeCoach.setStatus("1");
        storeCoach.setCreatedTime(new Date());
        result = storeCoachMapper.insertSelective(storeCoach);

        if (StringUtils.isNotBlank(coachInfo.getUrl())) {
            Resource videoResource = new Resource();
            videoResource.setParentId(coachInfo.getId());
            videoResource.setParentType("3");
            videoResource.setResType("2");
            videoResource.setUrl(coachInfo.getUrl());
            videoResource.setLink(coachInfo.getLink());
            videoResource.setResKey("coach_video");
            videoResource.setTitle("教练视频");
            result = resourceMapper.insertSelective(videoResource);
        }
        if (StringUtils.isNotBlank(coachInfo.getCategoryPic())) {
            String[] catePics = coachInfo.getCategoryPic().split(",");
            Resource catePicResource;
            for (String pic : catePics) {
                catePicResource = new Resource();
                catePicResource.setParentId(coachInfo.getId());
                catePicResource.setParentType("3");
                catePicResource.setResType("1");
                catePicResource.setUrl(pic);
                catePicResource.setResKey("coach_category");
                catePicResource.setTitle("教练类别硬照");
                result = resourceMapper.insertSelective(catePicResource);
            }
        }
        //私教案例
        if(StringUtils.isNotBlank(coachInfo.getResourceSampleTitle())
                && StringUtils.isNotBlank(coachInfo.getResourceSampleUrl())){
            Resource privateSampleTitleResource = new Resource();
            privateSampleTitleResource.setParentId(coachInfo.getId());
            privateSampleTitleResource.setParentType("3");
            privateSampleTitleResource.setResType("3");//链接
            privateSampleTitleResource.setResKey("coach_private_sample");
            privateSampleTitleResource.setTitle("私教案例");
            privateSampleTitleResource.setText(coachInfo.getResourceSampleTitle());
            privateSampleTitleResource.setUrl(coachInfo.getResourceSampleUrl());
            result = resourceMapper.insertSelective(privateSampleTitleResource);
        }


        return result > 0;
    }


    /**
     * 将支持私教的教练加入教练轮排表中轮排
     *
     * @return true 插入成功 / false 插入失败
     * @author blank 2017/8/11 下午5:52
     */
    private boolean joinCoachToCoachPrivateSort(CoachInfo coachInfo) {
        //先查询此教练是否支持私教轮排 支持私教轮排才继续下一步
        if (coachInfo.getIsPrivateCoachSort()!= null && coachInfo.getIsPrivateCoachSort().equals(1)) {

            //先查询此教练在教练轮排表中是否已经存在
            CoachPrivateSort coachPrivateSortQuery = new CoachPrivateSort();
            coachPrivateSortQuery.setCoachId(coachInfo.getId());
            coachPrivateSortQuery = coachPrivateSortMapper.selectOne(coachPrivateSortQuery);
            if (coachPrivateSortQuery == null) {

                //保存新教练到教练轮排表中 更新轮排顺序为当前最大排序减 1
                //查询当前教练轮排表中的最大排序
                int sortNow =  coachPrivateSortMapper.queryMinSortNow();
                int sortNum =  coachPrivateSortMapper.queryNextSortNum();
                CoachPrivateSort coachPrivateSort = new CoachPrivateSort();
                coachPrivateSort.setCoachId(coachInfo.getId());
                coachPrivateSort.setSortNum(sortNum);
                coachPrivateSort.setSortNow(sortNow);
                coachPrivateSort.setStatus(1);
                if (coachInfo.getSysUser()!= null && coachInfo.getSysUser().getId() != null) {
                    coachPrivateSort.setCreatedBy(coachInfo.getSysUser().getId());
                }
                coachPrivateSort.setCreatedBy(-1);
                coachPrivateSort.setCreatedTime(new Date());
                boolean r = coachPrivateSortMapper.insertSelective(coachPrivateSort) > 0 ;
                if (!r) {
                    System.err.println("教练新增时 插入教练排序表出错!");
                }
                return r;
            }
        }
        return false;
    }

    /**
     * 教练分页查询
     * @param paramsMap
     * @return resultMap
     */
    @Override
    public Map<String, Object> queryCoachPageList(Map<String, Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap<>();
        paramsMap.put("pageIndex",(Integer)paramsMap.get("pageIndex") * (Integer)paramsMap.get("pageSize"));
        resultMap.put("coachList", coachInfoMapper.queryCoachList(paramsMap));
        resultMap.put("coachCount", coachInfoMapper.queryCoachCount(paramsMap));

        return resultMap;
    }

    /**
     * 根据教练ID查询教练
     * @param id
     * @return
     */
    @Override
    public CoachInfo queryCoachById(Integer id) {
        if (id == null )
            return  null;

        CoachInfo coachInfo = coachInfoMapper.queryCoachByID(id);
        if (coachInfo.getResources() != null && coachInfo.getResources().size() > 0) {
            List<Resource> resources = coachInfo.getResources();
            StringBuilder sCatePic = new StringBuilder();
            for (Resource resource : resources) {


                if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("coach_video")) {
                    coachInfo.setUrl(resource.getUrl());
                    coachInfo.setLink(resource.getLink());
                }
                if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("coach_private_sample")) {//私教案例
                    coachInfo.setResourceSampleUrl(resource.getUrl());
                    coachInfo.setResourceSampleTitle(resource.getText());
                }
                if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("coach_category")) {
                    if (sCatePic.length() <= 0) {
                        sCatePic.append(resource.getUrl());
                    } else {
                        sCatePic.append("," + resource.getUrl());

                    }
                }
            }
            if (sCatePic.length() > 0) {
                coachInfo.setCategoryPic(sCatePic.toString());
            }
        }
        return coachInfo;
    }

    /**
     * 根据教练ID删除教练
     * @param id
     * @return
     */
    @Override
    public boolean delCoachById(Integer id) {
        resourceMapper.deleteByCoachId(id);
        return coachInfoMapper.deleteById(id) > 0;
    }

    /**
     * 教练离职
     * @param id
     * @return
     */
    @Override
    public boolean offlineCoachById(Integer id){
        if (id == null)
            return false;
        CoachInfo coachInfo = new CoachInfo();
        coachInfo.setId(id);
        coachInfo.setStatus(CoachConstants.CoachStatus.inserting_winding.getStatus());
        try {
            return coachInfoMapper.updateSelectiveById(coachInfo) > 0;
        } finally {
            deleteFormCoachPrivateSort(id);
        }
    }

    /**
     * 从教练轮排表中删除离职教练
     *
     * @param coachId 要删除的教练 ID
     * @return true 删除成功 / false 删除失败
     * @author blank 2017/8/9 上午9:45
     */
    private boolean deleteFormCoachPrivateSort(Integer coachId){

        CoachPrivateSort coachPrivateSort = new CoachPrivateSort();
        coachPrivateSort.setCoachId(coachId);
        return coachPrivateSortMapper.deleteSelective(coachPrivateSort) > 0;
    }

    /**
     * 查询教练列表 只返回 ID /nickName
     *
     * @return 返回教练列表 只返回 ID /nickName
     * @author blank 2017/7/31 下午9:16
     */
    @Override
    public List<CoachInfo> queryCoachIdAndNickName() {

        CoachInfo coachInfo = new CoachInfo();
        coachInfo.setStatus("1");
        coachInfo.setIsPrivate(CoachConstants.CoachSupportStatus.SUPPORT.getIndex());
        EntityWrapper<CoachInfo> entityWrapper = new EntityWrapper<>(coachInfo);

        List<CoachInfo> coachInfoList = coachInfoMapper.selectList(entityWrapper);
        List<CoachInfo> coachInfos = new ArrayList<>();
        coachInfoList.forEach(coach -> {
            CoachInfo c = new CoachInfo();
            c.setId(coach.getId());
            c.setNickName(coach.getNickName());
            coachInfos.add(c);
        });
        return coachInfos;
    }


    /**
     * 私教教练修改排序
     *
     * @return 修改条数
     * @author blank 2017/8/7 下午4:29
     */
    @Override
    public Integer updateSort(String sortString) {
        sortString = sortString.replace("##undefined", "");
        String [] IndexResourceIds = sortString.split("##");
        CoachInfo indexResource;
        List<CoachInfo> list = new ArrayList<>();
        for(int i = 1; i <= IndexResourceIds.length; i++){

            String idString  = IndexResourceIds[i-1];
            if (StringUtils.isNotBlank(idString)) {

                if (idString.contains("hf_")) {

                    idString = idString.replace("hf_", "");
                    String[] str = idString.split("_");
                    Integer id = Integer.valueOf(str[0]);

                    indexResource = new CoachInfo();
                    indexResource.setId(id);
                    indexResource.setSortNum(i);
                    list.add(indexResource);
                }
            }
        }
        if ( list.size() > 0) {
            return coachInfoMapper.updateBatchById(list);
        }
        return 0;

    }
    
    
	@Override
	public List<CoachInfo> queryAllCoachInfoByCoachType(Map<String, Object> parm) {
		List<CoachInfo> coachList = coachInfoMapper.queryCoachAllListByCoachType(parm);
		return coachList;
	}

    /**
     * 查询所有私教轮排数据
     *
     * @return 所有私教轮排数据
     * @author blank 2017/8/25 下午1:03
     */
    @Override
    public Map<String, Object> queryCoachPrivateSortList(Map<String, Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap<>();

        List<CoachPrivateSortModel> coachPrivateSortModels = coachPrivateSortMapper.queryCoachPrivateSortList(paramsMap);
        resultMap.put("list", coachPrivateSortModels);
        resultMap.put("count", coachPrivateSortModels.size());
        return resultMap;
    }


}
